// 读取 JSON 数据并动态生成服务图标
fetch("./json/service-icons.json")
  .then(response => response.json())
  .then(data => {
    const container = document.getElementById("service-container");

    data.forEach(item => {
      const serviceItem = document.createElement("div");
      serviceItem.innerText = item.name;

      container.appendChild(serviceItem);
    });
  })
  .catch(error => {
    console.error("加载 JSON 数据失败", error);
  });

// 登录状态

// 获取相关元素
const loginBtn = document.getElementById("login-btn");
const modal = document.getElementById("login-modal");
const closeModal = document.getElementById("close-modal");
const submitLogin = document.getElementById("submit-login");
const usernameInput = document.getElementById("username");
const passwordInput = document.getElementById("password");
const userAvatar = document.getElementById("user-avatar");
const loginStatus = document.getElementById("login-status");

// 从 localStorage 中读取用户信息
const storedUsername = localStorage.getItem("username");
let isLoggedIn = storedUsername !== null; // 如果有用户名则认为已登录
let currentUsername = storedUsername || ""; // 如果没有用户名则为空

// 如果已经登录，则设置页面显示
if (isLoggedIn) {
  userAvatar.src = `./imgs/avatr12.png`;
  loginStatus.textContent = `欢迎, ${currentUsername}!`;
  loginBtn.textContent = "退出登录";
}

// 弹出登录弹窗
loginBtn.addEventListener("click", () => {
  if (!isLoggedIn) {
    modal.style.display = "flex"; // 显示弹窗
  } else {
    // 如果已登录，点击“退出登录”
    logout();
  }
});

// 退出登录函数
function logout() {
  isLoggedIn = false;
  currentUsername = "";
  userAvatar.src = "avatar.png"; // 恢复默认头像
  loginStatus.textContent = "登录查看个人主页";
  loginBtn.textContent = "立即登录"; // 改为“立即登录”

  // 清除本地存储中的用户名
  localStorage.removeItem("username");
}

// 关闭弹窗
closeModal.addEventListener("click", () => {
  modal.style.display = "none"; // 隐藏弹窗
});

// 登录按钮点击事件
submitLogin.addEventListener("click", () => {
  const username = usernameInput.value.trim();
  const password = passwordInput.value.trim();

  // 简单的表单验证
  if (username === "" || password === "") {
    alert("请输入用户名和密码！");
    return;
  }

  // 设置登录状态
  isLoggedIn = true;
  currentUsername = username;
  userAvatar.src = `./imgs/avatr12.png`; // 头像API
  loginStatus.textContent = `欢迎, ${username}!`;
  loginBtn.textContent = "退出登录"; // 改为“退出登录”

  // 将用户名存储到本地存储
  localStorage.setItem("username", username);

  // 关闭弹窗
  modal.style.display = "none";
});
